from travel.models import Travel, City
from user.models import User
from travel.serializers import CityModelSerializer, Comments, CommentsModelSerializer, TravelModelSerializer
from user.serializers import UserComments, UserCommentsSerializer, User, UserModelSerializer
from travel.utils import public_travel_data
import pandas as pd
from django.db.models import Q

# 获取所有景点的DataFrame对象
df = public_travel_data.TravelDataFrame()


# 首页tag
def get_tags():
    # 景点数量
    travel_total = Travel.objects.all().values().count()

    # 热门景点
    hot_travel = df.sort_values(by='sale_count', ascending=False)['name'][0]

    arr = df['star'].value_counts().sort_index().to_dict()

    # 5a景点个数
    a5_travel = arr['5A']

    city_dict = df['city_id'].value_counts().sort_index().to_dict()
    city_id = list(city_dict.keys())[0]

    # 拥有景点个数最多的城市
    city_name = City.objects.get(id=city_id).name

    # 用户数量
    user_count = User.objects.all().count()

    res = {
        'travel_total': travel_total,
        'hot_travel': hot_travel,
        'a5_travel': a5_travel,
        'city_name': city_name,
        'user_count': user_count
    }

    return res


# 获取各城市景点数量
def getMapData():
    data = []
    arr = df.groupby('city_id')['star'].count().to_dict()
    for key, value in arr.items():
        city_name = CityModelSerializer(City.objects.get(id=key)).data['name']
        data.append({
            'name': city_name,
            'value': value
        })

    return data


# 获取热度前5的景点
def getTopTravel():
    data = df.sort_values(by=['comment_total'], ascending=False).iloc[:5, :]
    travels = list(data['name'])
    values = list(int(x) for x in data['comment_total'])
    res = {
        'travels': travels,
        'values': values,
    }
    return res


# 获取景点等级占比
def getTravelStar():
    star_dict = df.groupby('star')['star'].value_counts().to_dict()
    res = []
    for key, value in star_dict.items():
        res.append({
            'name': key,
            'value': value
        })

    return res


# 根据城市id获取所属城市的所有景点且排名
def getTravelListByCityId(city_id):
    # 根据城市id获取景点
    travel_list = list(Travel.objects.filter(city_id=city_id).values())
    travel_df = pd.DataFrame(travel_list)
    # 安装评论总数降序排序，
    data = travel_df.sort_values(by=['comment_total'], ascending=False)[::]
    values = data.values
    # 获取所有字段名
    names = [x for x in data]
    travels = []
    # 遍历排序后的景点数据，因为排序后的形式是数组形式，所以需要重新组装一下
    for value in values:
        travel_dict = dict(zip(names, value))
        travels.append(travel_dict)

    return travels


# 根据评论数获取热度排名的景点
def getHotTravelData(num):
    data = df.sort_values(by=['comment_total'], ascending=False).iloc[:num, :]

    values = data.values
    # 获取所有字段名
    names = [x for x in data]
    travels = []
    # 遍历排序后的景点数据，因为排序后的形式是数组形式，所以需要重新组装一下
    for value in values:
        travel_dict = dict(zip(names, value))
        travels.append(travel_dict)

    return travels


# 获取指定景点详情
def getTravelDetail(travelId, userId):
    # 查询景点信息
    travel = TravelModelSerializer(Travel.objects.get(id=travelId)).data
    # 查询该景点评论
    db_comments = UserCommentsSerializer(UserComments.objects.filter(travel=travelId), many=True).data
    if userId:
        try:
            # 当前登录用户对该景点的评论
            user_comment = UserComments.objects.get(user=userId, travel=travelId)
            db_user_comment = UserCommentsSerializer(user_comment).data
        except:
            db_user_comment = ''
    else:
        db_user_comment = ''
    comments = []
    for comment in db_comments:
        user_id = comment['user']
        user = UserModelSerializer(User.objects.get(id=user_id)).data
        comment['user'] = user
        comments.append(comment)

    res = {
        'travel': travel,
        'comments': comments,
        'userComment': db_user_comment
    }
    return res
